-- UIPetShop
-- Create by chendh
-- 冈布奥兑换界面

require "game/ui/form/hero/HeroUtil"
require "game/ui/form/hero/UIHeroDetailInfo"
require "game/ui/form/shop/UIPetShopGoodsDetail"

-- UIPetShop继承自Layer
UIPetShop = class("UIPetShop", function()
    return cc.Layer:create();
end);

function UIPetShop.create(campId, openType)
    return UIPetShop.new(campId, openType);
end

-- 商品格最大行数和列数
local MAX_GRID_ROW    = 2;
local MIN_GRID_COLUMN = 3;

-- 内部函数声明

-- 构造函数
function UIPetShop:ctor(campId, openType)
    -- 初始化
    self:setName("UIPetShop");
    local node = cc.CSLoader:createNode("layout/shop/BlackMarket.csb");
    self:addChild(node);
    self.node = node;
    self.campId = campId;

    self.openType = openType;

    local CT = node:getChildByName("CT");
    local scrollview = CT:getChildByName("scroll_view");
    self.CT = CT;
    self.scrollView = scrollview;
    self.scrollView:setVisible(true);

    -- 水平滑动，需要显示左右蒙版
    local mask3 = findChildByName(self.node, "CT/mask3");
    mask3:setVisible(true);
    local mask4 = findChildByName(self.node, "CT/mask4");
    mask4:setVisible(true);

    -- 修改滚动方向
    -- 1 垂直
    -- 2 水平
    self.scrollView:setDirection(2);

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UIPetShop:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- mask居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "mask");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 初始化商品格
function UIPetShop:initGoodsGrids(node)
    local w = DESIGN_WIDTH;
    local h = DESIGN_HEIGHT;

    -- 图标间距(横向)
    local wGap = 23;

    -- 图标间距(纵向)
    local hGap = 33;

    -- 图标宽度
    local iconWidth = 128;

    -- 图片高度
    local iconHeight = 163;

    local topHGap  = 100;
    local leftWGap = 20;

    -- 收集商品信息
    local goodsList = self:gatherGoodsInfo();

    -- 商品的共个数
    local shopCount = #goodsList;

    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();

    if shopCount <= 6 then
        -- 6个以下物品修正
        leftWGap = 33;
    end

    local itemNode = cc.CSLoader:createNode("layout/shop/PetShopItem.csb");

    -- @param windowNode    界面节点
    -- @param scrollNode    容器节点
    -- @param itemNode      单元格的节点
    -- @param totalNum      单元格总数
    -- @param maxRowNum     最大行数
    -- @param pageColNum    单页可以显示下的列数
    -- @param wGap          单元格间距(横向) 这里作为最小值使用
    -- @param hGap          单元格间距(纵向)
    -- @param iconWidth     单元格宽度
    -- @param iconHeight    单元格高度
    -- @param topHGap       上方留
    -- @param leftWGap      左右留白  这里作为最小值使用
    -- @param touchEvent    点击事件注册函数
    initScrollGridsHorizontal(self, self.scrollView, itemNode, shopCount, MAX_GRID_ROW, MIN_GRID_COLUMN, wGap, hGap, iconWidth, iconHeight, topHGap, leftWGap, self.registerPetShopTouchEvent);
end

-- 清空所有的商品格
function UIPetShop:clearAllGrid()
    -- 格子总数
    local totalGridCount = MAX_GRID_ROW * MIN_GRID_COLUMN;
    for i = 1, totalGridCount do
        local grid = self.scrollView:getChildByName("item" .. i);
        if grid then
            grid:setVisible(false);
        end
    end
end

-- 重绘
function UIPetShop:redraw()
    -- 去除所有
    self.scrollView:removeAllChildren();
    local soldOutTipsLabel = findChildByName(self.node, "CT/sold_out_tips");
    local slimeImage = findChildByName(self.CT, "slime");
    soldOutTipsLabel:setVisible(false);
    slimeImage:setVisible(false);

    -- 初始化商品格子
    self:initGoodsGrids(self.node);

    -- 重绘界面
    self:redrawPet();
end

-- 显示商品信息
function UIPetShop:redrawGoods(goodsList)
    -- 显示商品信息
    local totalGoodsCount = #goodsList;
    for i = 1, totalGoodsCount do
        local grid          = self.scrollView:getChildByName("item" .. i);
        local goodsBg       = grid:getChildByName("bg");
        local iconImg       = grid:getChildByName("goods_icon");
        local moneyImg      = grid:getChildByName("money_icon");
        local moneyLabel    = grid:getChildByName("money_count");
        local soldOutLabel  = grid:getChildByName("sold_out");
        local rankNode      = grid:getChildByName("star_node");
        local countLabel    = grid:getChildByName("item_count");

        goodsBg:loadTexture("images/ui/lictor/bg1.png");
        goodsBg:setScaleX(1.1);
        goodsBg:setScaleY(1.2);

        if i <= totalGoodsCount then
            grid:setVisible(true);

            local goodsIndex = goodsList[i][1];   -- 商品序号
            local goodsId    = goodsList[i][2];   -- 商品id
            local classId    = goodsList[i][3];   -- 宠物class_id
            local goodsIcon  = goodsList[i][4];   -- 商品图标
            local payAttrib  = goodsList[i][5];   -- 支付属性
            local goodsPrice = goodsList[i][6];   -- 商品价格
            local itemName   = goodsList[i][7];   -- 物品名称
            local rank       = goodsList[i][8];   -- 阶位

            -- 为商品图标绑定信息
            iconImg.goodsIndex = goodsIndex;
            iconImg.goodsId    = goodsId;
            iconImg.classId    = classId;
            iconImg.goodsIcon  = goodsIcon;
            iconImg.payAttrib  = payAttrib;
            iconImg.goodsPrice = goodsPrice;
            iconImg.itemName   = itemName;
            iconImg.rank       = rank;
            iconImg.goodsType  = self.shopType;

            -- 显示商品阶位
            local layer = createStarLayer(rank, "images/ui/symbol/star_little.png", "center", -0.7);
            if layer then
                rankNode:removeAllChildren();
                rankNode:addChild(layer);
            end
            -- 右上角数量不需要
            countLabel:setVisible(false);

            -- 显示商品图标/兑换花费
            iconImg:loadTexture(getHeroIconPath(goodsIcon));
            moneyImg:setPositionX(moneyImg:getPositionX() - 20);
            moneyLabel:setPositionX(moneyLabel:getPositionX() + 5);

            local iconPath;
            iconPath = getItemIconPath(payAttrib);
            moneyImg:loadTexture(iconPath);
            -- 需要缩小
            moneyImg:setScale(0.45);
            moneyLabel:setString(tostring(goodsPrice));
            moneyLabel:setPositionY(moneyLabel:getPositionY() - 3);

            TextStyleM.setTextStyle(moneyLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_WHITE, true);
            moneyLabel:getVirtualRenderer():setAdditionalKerning(getLocKerning() -3);
            if ItemM.getAmount(ME.user, payAttrib) < goodsPrice then
                moneyLabel:setTextColor(TextStyleM.TEXT_COLOR_LIGHT_RED);
            else
                moneyLabel:setTextColor(TextStyleM.TEXT_COLOR_WHITE);
            end

            -- 居中显示
            local moneyImgW = moneyImg:getContentSize().width;
            moneyImg:setPositionY(moneyImg:getPositionY() - 2 );
            local moneyLabelW = moneyLabel:getContentSize().width;

            moneyLabel:setPositionX(moneyLabel:getPositionX() + 15);
            moneyLabel:setPositionY(moneyLabel:getPositionY() - 1 );

            -- 判断商品已经是否售完
            local soldOut = false;
            if self.shopType == PETSHOP_TYPE_SCRAP then
                if PetShopM.getGoodInfoInShop(goodsId)["sold_out"] == 1 then
                    soldOut = true;
                    iconImg.soldOut = true;
                end
            end

            if soldOut then
                setGrayTransMode(goodsBg, true);
                setGrayTransMode(iconImg, true);

                -- 不显示价格，星星
                moneyImg:setVisible(false);
                moneyLabel:setVisible(false);
                rankNode:setVisible(false);

                -- 已兑换字样
                soldOutLabel:setVisible(true);
                TextStyleM.setTextStyle(soldOutLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_ORANGE, true);
                soldOutLabel:getVirtualRenderer():setAdditionalKerning(getLocKerning() -3);
                soldOutLabel:setString(getLocStr("has_been_exchange"));
            else
                -- 背景变亮
                setGrayTransMode(goodsBg, false);
                setGrayTransMode(iconImg, false);

                -- 显示图标、价格、星星
                moneyImg:setVisible(true);
                moneyLabel:setVisible(true);
                rankNode:setVisible(true);

                soldOutLabel:setVisible(false);
            end
        else
            -- 清空多余的格子
            grid:setVisible(false);
        end
    end
end

-- 显示宠物商店
function UIPetShop:redrawPet()
    -- 显示标题
    local titleLabel = findChildByName(self.CT, "title");
    TextStyleM.setTitleStyle(titleLabel);

    -- 获取阵营名称
    local name;
    if self.openType == "SkyPetShop" then
        name = getLocStr("sky_pet_shop");
    else
        name = CampM.query(self.campId, "name");
    end
    titleLabel:setString(name);

    local descLabel = findChildByName(self.CT, "subhead");
    TextStyleM.setSubheadStyle(descLabel);

    -- 当前可以兑换的冈布奥数量
    local num;
    if self.openType == "SkyPetShop" then
        num = #SkyPetShopM.getCanRecruitIds();
    else
        num = #PetShopM.getGoodsNumByCamp(self.campId);
    end
    descLabel:setString(string.format(getLocStr("slime_num"), num));

    -- 售罄提示
    local kerning = 0;
    if getLang() ~= "zh" and getLang() ~= "tw" then
        kerning = -2;
    end
    local soldOutTipsLabel = findChildByName(self.CT, "sold_out_tips");
    local slimeImage = findChildByName(self.CT, "slime");
    TextStyleM.setTextStyle(soldOutTipsLabel, TextStyleM.TEXT_SIZE_MIDDLE2, TextStyleM.TEXT_COLOR_GRAY, false, kerning);
    soldOutTipsLabel:setString(getLocStr("pet_sold_out_tips"));
    slimeImage:loadTexture(getHeroLargeIconPath(1));

    -- 收集商品信息
    local goodsList = self:gatherGoodsInfo();

    if not goodsList or #goodsList == 0 then
        cclog("收集商品信息失败。");
        self:clearAllGrid();

        -- 商品售罄了，需要显示售罄的提示
        soldOutTipsLabel:setVisible(true);

        -- 冈布奥图片
        slimeImage:setVisible(true);
        slimeImage:setOpacity(128);
        slimeImage:setScale(0.7);
        return;
    else
        soldOutTipsLabel:setVisible(false);
        slimeImage:setVisible(false);
    end

    -- 绘制商品信息
    self:redrawGoods(goodsList);
end

-- 佣兵营地
function UIPetShop:getRecruitInfo()
    -- 获取本店的所有商品
    -- 按阵营获取

    local goodsList;
    if self.openType == "SkyPetShop" then
        goodsList = SkyPetShopM.querySkySlimes();
    else
        goodsList = PetShopM.getGoodsByCamp(self.campId);
    end
    if goodsList == nil then
        return nil;
    end
    local ret = {};
    local goodsIndex = 1;  -- 商品的序号
    for _, info in ipairs(goodsList) do
        local goodsId    = info.id;
         local arr;
        if "SkyPetShop" == self.openType then
            arr = SkyPetShopM.queryPrice(goodsId);
        else
            arr = PetShopM.queryPrice(goodsId);
        end

        local payAttrib  = arr[2];           -- 支付属性
        local goodsPrice = arr[3];           -- 商品价格
        local classId    = info["pet_id"];
        local petInfo    = PetM.query(classId);
        if not ME.user.pets[classId] and ItemM.getAmount(ME.user, payAttrib) >= 0 then
            table.insert(ret, {goodsIndex, goodsId, classId, PetM.getDefaultIcon(classId), payAttrib, goodsPrice,
                PetM.query(classId, "name"), petInfo["init_rank"]});
        end

        goodsIndex = goodsIndex + 1;
    end
    return ret;
end

-- 获取可购买的商品信息
function UIPetShop:gatherGoodsInfo()
    return self:getRecruitInfo();
end

-- 当商品被点击
function UIPetShop:onGoodsClick(iconImg)
    if iconImg.soldOut then
        alert("goods_exchange_already");
        return;
    end

    -- 显示商品详细信息
    UIMgr.getCurrentScene():removeFormByName("UIHeroDetailInfo");
    local uiGoodsDetail;
    if "SkyPetShop" == self.openType then
        uiGoodsDetail = UIHeroDetailInfo.create(iconImg.classId, "SkyPetShop", iconImg.goodsId);
    else
        uiGoodsDetail = UIHeroDetailInfo.create(iconImg.classId, "petShop", iconImg.goodsId);
    end
    UIMgr.getCurrentScene():addForm(uiGoodsDetail);
end

-- 注册商品点击事件
function UIPetShop:registerPetShopTouchEvent(node)
    -- 注册商品图标点击事件
    local image = node:getChildByName("bg");
    local iconImg = node:getChildByName("goods_icon");
    local function onClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_spell");
            -- 仅处理非空的格子
            if type(iconImg.goodsIcon) == 'number' then
                self:onGoodsClick(iconImg);
            end
        end
    end
    image:addTouchEventListener(onClick)
end

-- 注册事件处理回调函数
function UIPetShop:registerEventCallback()
    -- 关注激活宠物时间
    EventMgr.register("UIPetShop", event.GAIN_PET, function()
        -- 初始化商品格子
        self:initGoodsGrids(self.node);

        -- 默认滑到最左侧
        scrollToTopLeft(self.scrollView);

        self:redrawPet();
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UIPetShop", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIPetShop" then
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM);
        end
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UIPetShop 界面析构清理");
            EventMgr.removeAll("UIPetShop");
        elseif eventType == "enter" then
        end
    end);
end

-- 注册点击事件
function UIPetShop:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIPetShop");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 设置按钮
    local btnSet = findChildByName(self.node, "BT/refresh");
    btnSet:setVisible(false);
end